package com.seek.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seek.eduservice.entity.EduChapter;
import com.seek.eduservice.entity.EduVideo;
import com.seek.eduservice.entity.subject.Chapter;
import com.seek.eduservice.entity.subject.Video;
import com.seek.eduservice.mapper.EduChapterMapper;
import com.seek.eduservice.mapper.EduVideoMapper;
import com.seek.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wml
 * @since 2022-01-16
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoMapper eduVideoMapper;

    // 课程大纲列表，根据课程 id 进行查询
    @Override
    public List<Chapter> getChapterAndVideoByCourseId(String courseId) {
        List<Chapter> chapters = new ArrayList<>();
        List<Video> videos = null;
        Chapter chapter = null;
        Video video = null;
        EduVideo eduVideo = null;

        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", courseId);
        List<EduChapter> eduChapters = baseMapper.selectList(chapterQueryWrapper);
        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", courseId);
        List<EduVideo> eduVideos = eduVideoMapper.selectList(videoQueryWrapper);

        for (EduChapter eduChapter : eduChapters) {
            chapter = new Chapter();
            BeanUtils.copyProperties(eduChapter, chapter);
            videos = new ArrayList<>();
            for (int i = 0; i < eduVideos.size(); i++) {
                eduVideo = eduVideos.get(i);
                if (eduVideo.getChapterId().equals(chapter.getId())) {
                    video = new Video();
                    BeanUtils.copyProperties(eduVideo, video);
                    videos.add(video);
                    eduVideos.remove(eduVideo);
                    i--;
                }
            }
            chapter.setChildren(videos);
            chapters.add(chapter);
        }
        return chapters;
    }

    // 根据课程 id 删除章节
    @Override
    public void removeByCourseId(String courseId) {
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        baseMapper.delete(queryWrapper);
    }
}
